package at.fhj.swd10.eshop.web.view;

import at.fhj.swd10.eshop.database.UserDao;
import at.fhj.swd10.eshop.domain.User;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.apache.commons.lang.StringUtils;

/**
 * @author David
 */
@ManagedBean
@ViewScoped
public class RegisterBacking implements Serializable {

    private UserDao userDao = UserDao.getUserDao();
    private String username;
    private String password;
    private String password2;

    public String register() throws Exception {
        if (!StringUtils.equals(password, password2)) {
            FacesContext.getCurrentInstance().addMessage("register", new FacesMessage("registration not successful - passwords not equal"));
            return "register";
        }

        if (userDao.getUserByUsername(username) != null) {
            FacesContext.getCurrentInstance().addMessage("register", new FacesMessage("registration not successful - user already exists"));
            return "register";
        }

        userDao.insertUser(new User(username, password, false));
        return "login";
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPassword2() {
        return password2;
    }

    public void setPassword2(String password2) {
        this.password2 = password2;
    }
}
